module Logins.ShopLogin exposing (..)

import Html exposing (Html,br, a, button, code, div, h1, li, text, ul, input)
import Html.Events exposing (onInput,onClick)
import Http
import Json.Encode as Encode
import Json.Decode as Decode
import Logins.Common as Common
import Navigation exposing (newUrl)

type Msg 
 = NameInput Name 
 | PassInput Pass
 | Confirm
 | LoginResult (Result Http.Error (Result String String))

type alias Name = String
type alias Pass = String
type alias Log = String

type Model = Model Name Pass Log

initModel : Model
initModel = Model "" "" ""

view : Model -> Html Msg
view (Model _ _ log) =
 div [] 
  [ text "店家名: "
  , input [ onInput NameInput ] [ ]
  , text "密码: "
  , input [ onInput PassInput ] [ ]
  , button [ onClick Confirm ] [text "登录"]
  , br [] []
  , text ("Logger: " ++ log)]

update : Msg -> Model -> (Model,Cmd Msg)
update msg ((Model oldName oldPass log) as model) =
 case msg of
  NameInput name ->
   (Model name oldPass log,Cmd.none)
 
  PassInput pass ->
   (Model oldName pass log,Cmd.none)

  Confirm ->
   let 
    json = Encode.object [("shop",Encode.string oldName),("pass",Encode.string oldPass)]
    body = Http.jsonBody json
    request = Http.post "/shop-end/op/login" body Common.loginResDecoder
   in (model, Http.send LoginResult request)

  LoginResult (Err _) -> (Model oldName oldPass "服务器响应错误!",Cmd.none)

  LoginResult (Ok res) ->
   case res of
    Err msg -> (Model oldName oldPass ("登录失败!" ++ msg),Cmd.none)

    Ok _ -> (Model oldName oldPass "登录成功!", newUrl "/#/shop-end/index")